package mypazar.customer;

import mypazar.agent.PersonAgent;
import mypazar.jenamodel.PazarVocabulary;
import tr.edu.ege.seagent.planner.htn.Action;
import tr.edu.ege.seagent.planner.htn.ExecutionMethod;
import tr.edu.ege.seagent.planner.htn.Provision;
import cartago.ArtifactId;
import cartago.CartagoException;
import cartago.Op;
import cartago.util.agent.CartagoBasicContext;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;

/**
 * Action class of ACAskAboutProduct.
 */
public class ACAskAboutProduct extends Action {

	/**
	 * SalesmanName provision.
	 */
	@Provision
	private String StallArtifactName;

	/**
	 * Returns the value of the SalesmanName provision.
	 */
	public String getStallArtifactName() {
		return this.StallArtifactName;
	}

	/**
	 * Sets the value of the SalesmanName provision.
	 */
	public void setStallArtifactName(String StallArtifactName) {
		this.StallArtifactName = StallArtifactName;
	}

	/**
	 * Execution method.
	 */
	@ExecutionMethod
	public void execute() {
		Model beliefBase = (Model) getHeapValue(PersonAgent.BELIEF_BASE_ITEM_NAME);

		ArtifactId artifactId = null;
		CartagoBasicContext ctX = (CartagoBasicContext) getHeapValue(PazarVocabulary.CTX_PERSON_ITEM_NAME);

		try {
			artifactId = ctX.lookupArtifact(getStallArtifactName());
			ctX.focus(artifactId);
		} catch (CartagoException e) {
			e.printStackTrace();
		}

		String PERSON_URI = PazarVocabulary.NS_URI
				+ getAgentIdentifier().toString().substring(0, 7);

		String productName = getProductName(beliefBase, PERSON_URI);

		try {
			ctX.doAction(artifactId, new Op("askAboutProduct", productName));
			// this.addReceiverAgent("salesman"
			// + getStallArtifactName().substring(5, 6) + "@mypazar.com");
			this.setOutcomeState("Inform");
			this.setOutcomeState("Failure");
		} catch (CartagoException e) {
			e.printStackTrace();
			this.setOutcomeState("Failure");
		}

		// set the outcome....

		// this.setProduct(getProductName(beliefBase, PERSON_URI));

		// add receiver agent...
		// this.addReceiverAgent(getSalesmanName() + "@mypazar.com");

	}

	/**
	 * Gets product name from belief base
	 * 
	 * @param beliefBase
	 * @param personURI
	 * @return
	 */
	private String getProductName(Model beliefBase, String personURI) {
		String pName = null;
		Resource resPerson = beliefBase.getResource(personURI);
		StmtIterator iterProduct = resPerson.listProperties(ResourceFactory
				.createProperty(PazarVocabulary.PRODUCT_URI));
		if (iterProduct.hasNext()) {
			Statement stmtProduct = iterProduct.next();
			Resource resProduct = stmtProduct.getObject().asResource();

			pName = resProduct
					.getProperty(
							ResourceFactory
									.createProperty(PazarVocabulary.PRODUCT_NAME_URI))
					.getLiteral().getString();
		}
		return pName;
	}
}
